import React, { Component } from 'react';
import _ from 'underscore';
import { transform, tools } from 'src/utils';
import List from 'components/common/list';


const FormList = (Wrapper) => {
  class WrapperComponent extends Component {

    getList = () => {
      this.props.dispatch({ type: `${this.props.type}/list` });
    }

    downLoad = (fields) => {
      const params = transform.fieldsToParams(fields, this.props.dateType === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD');
      const url = this.props.downloadUrl ? this.props.downloadUrl : `/api/score/${this.props.type}/download`;
      tools.download(url + transform.objectToHashString({ ...params}));
      this.props.dispatch({
        type: this.props.type + '/toggleDownload',
        payload: true,
      });
    }

    paramsChange = (params) => {
      this.props.dispatch({
        type: `${this.props.type}/paramsChange`,
        payload: params,
      });
    }

    listChange = (params) => {
      this.paramsChange(params);
      this.getList();
    }

    handleFormFields = (fields) => {
      const params = transform.fieldsToParams(fields);
      this.paramsChange({
        ...params,
        pageNo: 1,
      });
    }

    onSubmit = (fields) => {
      this.handleFormFields(fields);
      this.getList();
    }

    render() {
      const error = this.props.fieldErrors;
      const listClass = this.props.isHidden ? 'list-container hide' : 'list-container';

      return (
        <div className={listClass}>
          <Wrapper
            {...this.props}
            download = { this.downLoad }
            onSubmit = { this.onSubmit }
            autoSubmit = { true }
          />
          <div className="query-result clearfix">
            <List
              { ...this.props }
              dataSource={this.props.list}
              pagination={{ ...this.props.searchParams, current: this.props.searchParams.pageNo, total: this.props.total }}
              onChange={this.listChange}
            />
          </div>
        </div>
      );
    }
  }

  return WrapperComponent;
};

export default FormList;
